package com.zlzlib.libdata.util;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.util.Base64;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 图片处理工具
 * Created by zlz on 2017/10/27.
 */

public class MyBitmapUtil {

    /**
     * @param path
     * @param h
     * @param w
     * @return 得到圆形的bitmap
     */
    public static Bitmap createCircleBitmap(String path, float w, float h) {
        try {
            File file = new File(path);
            if (file.exists()) {
                if (w == 0 | h == 0) {
                    return circleBitmap(BitmapFactory.decodeFile(file.getAbsolutePath()));
                } else {
                    return circleBitmap(zoomBitmap(BitmapFactory.decodeFile(file.getAbsolutePath()), w, h, true, false));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @param path
     * @param h
     * @param w
     * @return 矩形圆角Bitmap
     */
    public static Bitmap createRoundBitmap(String path, float w, float h) {
        try {
            File file = new File(path);
            if (file.exists()) {
                if (w == 0 | h == 0) {
                    return roundBitmap(BitmapFactory.decodeFile(file.getAbsolutePath()));
                } else {
                    return roundBitmap(zoomBitmap(BitmapFactory.decodeFile(file.getAbsolutePath()), w, h, true, false));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * @param oPath
     * @param nPath
     * @param w
     * @param h
     * @return 压缩图片文件
     */
    public static File getPressImgFile(String oPath, String nPath, float w, float h) {
        try {
            File oFile = new File(oPath);
            if (oFile.exists()) {
                File nFile = new File(nPath);
                if (nFile.exists()) {
                    nFile.delete();
                }
                nFile.createNewFile();
                ByteArrayOutputStream bao = new ByteArrayOutputStream();
                Bitmap bitmap = zoomBitmap(BitmapFactory.decodeFile(oPath), w, h, true, true);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bao);
                FileOutputStream fos = new FileOutputStream(nFile);
                fos.write(bao.toByteArray());
                fos.flush();
                fos.close();
                return nFile;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 缩放处理图片
     *
     * @param bm           所要转换的bitmap
     * @param newWidth     新的宽
     * @param newHeight    新的高
     * @param isEqualRatio 是否等比缩放
     * @param isZoomIn     是否缩小 true 为只缩小
     * @return 缩放的bitmap
     */
    public static Bitmap zoomBitmap(Bitmap bm, float newWidth, float newHeight, boolean isEqualRatio, boolean isZoomIn) {
        // 获得图片的宽高
        int width = bm.getWidth();
        int height = bm.getHeight();
        // 计算缩放比例
        float scaleWidth = newWidth / width;
        float scaleHeight = newHeight / height;
        // 取得想要缩放的matrix参数
        Matrix matrix = new Matrix();
        if (isEqualRatio) {
            float scale = 1;
            if (scaleWidth >= 1 && scaleHeight >= 1) {
                if (isZoomIn) {
                    return bm;
                }
                scale = Math.max(scaleWidth, scaleHeight);
            } else {
                scale = Math.min(scaleWidth, scaleHeight);
            }
            matrix.postScale(scale, scale);
        } else {
            if (isZoomIn) {
                scaleWidth = scaleWidth < 1 ? scaleWidth : 1;
                scaleHeight = scaleHeight < 1 ? scaleHeight : 1;
            }
            matrix.postScale(scaleWidth, scaleHeight);
        }
        // 得到新的图片
        return Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);
    }

    /**
     * @param file
     * @param w
     * @param h
     * @return 压缩图片
     */
    @Deprecated
    public static Bitmap pressBitmap(File file, float w, float h) throws IOException {
        InputStream input = new FileInputStream(file);
        BitmapFactory.Options onlyBoundsOptions = new BitmapFactory.Options();
        onlyBoundsOptions.inJustDecodeBounds = true;
        onlyBoundsOptions.inDither = true;//optional
        onlyBoundsOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;//optional
        BitmapFactory.decodeStream(input, null, onlyBoundsOptions);
        input.close();
        int originalWidth = onlyBoundsOptions.outWidth;
        int originalHeight = onlyBoundsOptions.outHeight;
        if ((originalWidth == -1) || (originalHeight == -1))
            return null;
//        //图片分辨率以240x400为标准
//        float hh = 400f;//这里设置高度为400f
//        float ww = 240f;//这里设置宽度为240f
        //缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        int be = 1;//be=1表示不缩放
        if (originalWidth >= originalHeight && originalWidth > w) {//如果宽度大的话根据宽度固定大小缩放
            be = (int) (originalWidth / w);
        } else if (originalWidth <= originalHeight && originalHeight > h) {//如果高度高的话根据宽度固定大小缩放
            be = (int) (originalHeight / h);
        }
        if (be <= 0) be = 1;
        //比例压缩
        BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
        bitmapOptions.inSampleSize = be;//设置缩放比例
        bitmapOptions.inDither = true;//optional
        bitmapOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;//optional
        input = new FileInputStream(file);
        Bitmap bitmap = BitmapFactory.decodeStream(input, null, bitmapOptions);
        input.close();
        return bitmap;
    }

    /**
     * @param srcBitmap
     * @return 生成圆形Bitmap
     */
    private static Bitmap circleBitmap(Bitmap srcBitmap) {
        if (srcBitmap == null) {
            return null;
        }
        int bmWidth = srcBitmap.getWidth();
        int bmHeight = srcBitmap.getHeight();
        int min = Math.min(bmWidth, bmHeight);
        Bitmap bitmap = Bitmap.createBitmap(min, min, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        canvas.drawCircle(min / 2f, min / 2f, min / 2f, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(srcBitmap, 0, 0, paint);
        return bitmap;
    }


    /**
     * @param srcBitmap
     * @return 生成矩形圆角Bitmap
     */
    private static Bitmap roundBitmap(Bitmap srcBitmap) {
        if (srcBitmap == null) {
            return null;
        }
        int bmWidth = srcBitmap.getWidth();
        int bmHeight = srcBitmap.getHeight();
        int min = Math.min(bmWidth, bmHeight);
        Bitmap bitmap = Bitmap.createBitmap(min, min, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        RectF rect = new RectF(0, 0, min, min);
        canvas.drawRoundRect(rect, 15, 15, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(srcBitmap, 0, 0, paint);
        return bitmap;
    }

    /**
     * 将本地图片文件转换成可解码二维码的 Bitmap。为了避免图片太大，这里对图片进行了压缩
     * 压缩大小  400
     *
     * @param picturePath 本地图片文件路径
     */
    public static Bitmap getDecodeAbleBitmap(String picturePath) {
        try {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(picturePath, options);
            int sampleSize = options.outHeight / 400;
            if (sampleSize <= 0) {
                sampleSize = 1;
            }
            options.inSampleSize = sampleSize;
            options.inJustDecodeBounds = false;
            return BitmapFactory.decodeFile(picturePath, options);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @param inputBitmap       旋转的图片
     * @param orientationDegree 角度
     * @return 旋转图片
     */
    public static Bitmap adjustPhotoRotation(Bitmap inputBitmap, int orientationDegree) {
        if (inputBitmap == null) {
            return null;
        }
        Matrix matrix = new Matrix();
        matrix.setRotate(orientationDegree, (float) inputBitmap.getWidth() / 2, (float) inputBitmap.getHeight() / 2);
        float outputX, outputY;
        if (orientationDegree == 90) {
            outputX = inputBitmap.getHeight();
            outputY = 0;
        } else {
            outputX = inputBitmap.getHeight();
            outputY = inputBitmap.getWidth();
        }
        final float[] values = new float[9];
        matrix.getValues(values);
        float x1 = values[Matrix.MTRANS_X];
        float y1 = values[Matrix.MTRANS_Y];
        matrix.postTranslate(outputX - x1, outputY - y1);
        Bitmap outputBitmap = Bitmap.createBitmap(inputBitmap.getHeight(), inputBitmap.getWidth(), Bitmap.Config.ARGB_8888);
        Paint paint = new Paint();
        Canvas canvas = new Canvas(outputBitmap);
        canvas.drawBitmap(inputBitmap, matrix, paint);
        return outputBitmap;
    }

    /**
     * @param path 文件地址
     * @return 图片文件转base64
     */
    public static String bitmapToBase64(String path) {
        String dataString = "";
        try {
            dataString = bitmapToBase64(BitmapFactory.decodeFile(path));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dataString;
    }

    /**
     * @param bmp 图片
     * @return 图片转base64
     */
    public static String bitmapToBase64(Bitmap bmp) {
        String dataString = "";
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bmp.compress(Bitmap.CompressFormat.PNG, 100, baos);
            dataString = android.util.Base64.encodeToString(baos.toByteArray(),
                    android.util.Base64.NO_WRAP | Base64.NO_PADDING);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dataString;
    }
}
